<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/7
 * Time: 11:14
 */

namespace App\LogicService;

use App\LogicService\Contracts\BloodDietLogicContract;
use App\Models\Dynamic\BloodDiet;
use App\Models\Dynamic\SamGlucose;
use Illuminate\Support\Facades\DB;


class BloodDietLogic extends BaseLogic implements BloodDietLogicContract
{
   public function getEatData($user_id, $startTime, $endTime, $type)
   {

       switch ($type) {
           case '1':
               $diettype = "早餐";
               break;
           case '2':
               $diettype = "午餐";

               break;
           default:
               $diettype = "晚餐";
               break;
       }

       $diet = BloodDiet::whereUserid($user_id)
           ->whereBetween('diettime', [$startTime, $endTime])
           ->whereDiettype($diettype)
           ->orderBy('diettime', 'desc')
           ->first();

       if (!$diet) {
           $return_data = array(
               'avg' => 0,
               'min' => 0,
               'max' => 0
           );
           return $return_data;
       }
       $start_time = $diet->diettime;
       $end_time = date('Y-m-d H:i:s',strtotime($start_time) + 2 * 60 * 60);



       //平均值最大值最小值
       $array = SamGlucose::getListByUIdByTime($user_id, $start_time, $end_time)
           ->select(DB::raw("AVG(value) as avg,MAX(value) as max,MIN(value) as min"))
           ->get()
           ->toArray();

       $return_data = array(
           'avg' => $array[0]['avg'],
           'min' => $array[0]['min'],
           'max' => $array[0]['max']
       );

       return $return_data;
   }
}
